/* eslint-disable quotes */
/* eslint-disable quote-props */
import { Grid, Pagination, Search, Table } from '@alifd/next';
import { t } from "@lingui/macro";
import React, { useState } from 'react';
import * as api from '../stores/api';

function getKind(type) {
  switch (type) {
    case 'user': return 'all';
    case 'userc': return 'console';
    case 'useri': return 'inet';
  }
}

const UserSelector = ({ type, setSelected, keyMapper = (k) => `${type}:${k}` }) => {
  const [selectedKeys, setSelectedKeys] = useState([]);
  const kind = getKind(type);
  const [state, setState] = useState({
    users: [],
    page: 0,
    total: 0,
    keyword: undefined,
    loading: false,
  });

  React.useEffect(() => {
    fetch();
  }, [type]);

  async function fetch() {
    setState({ ...state, loading: true });
    const { page, keyword } = state;
    const total = await api.getUserCount({ kind, keyword, page });
    const users = await api.getUsers({ kind, keyword, page });
    return setState({ ...state, users, total, loading: false });
  }

  const onSearch = (keyword) => {
    fetch();
  };

  return (
    <div>
      <Grid.Row>
        <Search shape="simple" type="normal" style={{ marginLeft: 'auto' }} value={state.keyword} onChange={(t) => setState({ ...state, keyword: t })} onSearch={onSearch} />
      </Grid.Row>
      <Grid.Row>
        <Grid.Col span={24}>
          <Table.StickyLock
            fixedHeader
            dataSource={state.users}
            primaryKey="username"
            hasBorder={false}
            loading={state.loading}
            rowSelection={{
              onChange: (keys) => { setSelectedKeys(keys) || setSelected(keys.map(keyMapper)); },
              selectedRowKeys: selectedKeys,
            }}
          >
            {/* <Table.Column title={t`序号`} width={80} cell={(v, i) => state.idx(i)} /> */}
            <Table.Column title={t`帐号`} dataIndex="username" />
            <Table.Column title={t`姓名`} dataIndex="fullname" align="center" />
            <Table.Column title={t`手机`} dataIndex="mobile" align="center" />
            <Table.Column title={t`邮件`} dataIndex="email" align="center" />
            <Table.Column title={t`状态`} dataIndex="status" align="center" cell={(v, i) => (v === 0 ? t`禁用` : t`正常`)} />
          </Table.StickyLock>
          <Pagination
            {...PGPROP}
            current={state.page + 1}
            total={state.total}
            onChange={(pgNo) => setState({ ...state, page: pgNo - 1 })}
          />
        </Grid.Col>
      </Grid.Row>
    </div>
  );
};

export default UserSelector;
